package com.minelx.treeftp;

import com.minelx.landisk.filesystem.core.Directory;
import com.minelx.landisk.filesystem.core.File;
import com.minelx.landisk.filesystem.stringnify.PathNavigator;

import java.io.IOException;
import java.nio.file.StandardOpenOption;
import java.util.Arrays;
import java.util.List;

import static com.minelx.landisk.filesystem.core.PathFactory.directory;
import static com.minelx.landisk.filesystem.core.PathFactory.file;
import static java.util.stream.Collectors.toList;

public class TreeDirectory {
	private final FileClient client;

	private final PathNavigator navigator;

	public TreeDirectory(String path, FileClient client) {
		this.client = client;
		navigator = PathNavigator.pathAt(path);
	}

	public List<TreeFile> listFiles() {
		return Arrays.stream(client.listFilesAt(navigator.toPathText()))
				.map(fileName -> new TreeFile(navigator.child(fileName).toPathText(), client))
				.collect(toList());
	}

	public List<TreeDirectory> listDirectories() {
		return Arrays.stream(client.listDirectoriesAt(navigator.toPathText()))
				.map(fileName -> new TreeDirectory(navigator.child(fileName).toPathText(), client))
				.collect(toList());
	}

	public String getName() {
		return navigator.currentFileName();
	}

	public void download(Directory destDirectory) {
		try {
			for (TreeFile file : listFiles()) {
				File destFile = destDirectory.child(file(), file.getName());
				file.read(destFile.outputStream(StandardOpenOption.CREATE));
			}
			// deal with all directories
			for (TreeDirectory childDirectory : listDirectories()) {
				Directory childFolder = destDirectory.child(directory(), childDirectory.getName());
				childFolder.createIfNotExists();
				childDirectory.download(childFolder);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
